<template>
  <div
    class="echarts"
    :id="randomId"
    style="height: 300px;"
  ></div>
</template>

<script>
export default {
  props: {
    option: {
      type: Object,
      default() {
        return {};
      },
    },
    randomId: {
      type: String,
      default() {
        return "myChart";
      },
    },
  },
  data() {
    return {};
  },

  mounted() {
    //# 1. 获取一个用于挂在 echarts 的 DOM 元素
    let $echartsDOM = document.getElementById(this.randomId);
    //# 2. 初始化
    this.myEcharts = this.$echarts.init($echartsDOM);
    this.checkAndSetOption();
  },
  beforeDestroy() {
    //组件卸载释放chart内存
    if (!!this.myEcharts) {
      this.myEcharts.clear(); //清空图表
      this.myEcharts.dispose(); //释放图表组件
      this.myEcharts = null;
    }
  },
  watch: {
    option(option) {
      this.checkAndSetOption();
    },
  },
  methods: {
    checkAndSetOption() {
      function isValidOption(option) {
        return (
          isObject(option) &&
          !isEmptyObject(option) &&
          hasSeriesKey(option) &&
          isSeriesArray(option) &&
          !isSeriesEmpty(option)
        );
      }

      function isObject(option) {
        return Object.prototype.isPrototypeOf(option);
      }

      function isEmptyObject(option) {
        return Object.keys(option).length === 0;
      }

      function hasSeriesKey(option) {
        return !!option["series"];
      }

      function isSeriesArray(option) {
        return Array.isArray(option["series"]);
      }

      function isSeriesEmpty(option) {
        return option["series"].length === 0;
      }
      let option = this.option;
      if (isValidOption(option)) {
        this.myEcharts.setOption(option);
        this.myEcharts.hideLoading();
      } else {
        this.myEcharts.showLoading();
      }
    },
  },
};
</script>